﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using Dry;
using Dry.DbInterpreter;
using System.Xml;
using CheckBox = System.Windows.Forms.CheckBox;
using Label=System.Windows.Forms.Label;
using RadioButton = System.Windows.Forms.RadioButton;

using System.CodeDom.Compiler;
using System.Diagnostics;

namespace WinApp
{
    public partial class frmDry : Form
    {
        private string _connectionStringDry;
        private string _outputDestination;
        private string _projectName;
        private string _tablePrefix;
        private bool _mspractices5;
        private bool _generateDryLog;
        private bool _generateLocalization;
        private bool _generateInnerJoinCode;

        private const string XmlFavorites = "c:\\dry\\favorites.xml";

        /// <summary>
        /// Constructor, dry is initialized
        /// </summary>
        public frmDry()
        {
            InitializeComponent();
            ProcessXml(XmlFavorites);
            ProgressInformation("Select or add a favorite.");
        }

        /// <summary>
        /// Dry has started
        /// </summary>
        private void frmDry_Load(object sender, EventArgs e)
        {
            ResizeControls();
        }

        #region FileSelection

        private void txtFile_MouseClick(object sender, MouseEventArgs e)
        {
            ShowFileDialog();
        }

        private void txtFile_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ShowFileDialog();
        }

        private void ShowFileDialog()
        {
            OpenFileDialog dlg = new OpenFileDialog();

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                txtFile.Text = dlg.FileName;
            }
        }

        private void btnFile_OK_Click(object sender, EventArgs e)
        {
            if (txtFile.Text != "")
            {
                StreamReader streamReader = new StreamReader(txtFile.Text);

                try
                {
                    ProgressInformation("Reading file to memory.");
                    ProgressBarValue(10, pbrTableProgressBar);

                    string strConfigFile = streamReader.ReadToEnd();
                    var lstConnectionString = new List<string>();

                    if (strConfigFile.Contains("<connectionStrings>"))
                    {
                        ProgressInformation("Looking for connectionstrings.");
                        ProgressBarValue(20, pbrTableProgressBar);

                        strConfigFile = strConfigFile.Substring(strConfigFile.IndexOf("<connectionStrings>"));
                        strConfigFile = strConfigFile.Substring(0, strConfigFile.IndexOf("</connectionStrings>"));

                        string _pattern = @"\<add ";

                        Regex r = new Regex(_pattern, RegexOptions.IgnoreCase);
                        MatchCollection ma = r.Matches(strConfigFile);

                        for (int i = 0; i < ma.Count; i++)
                        {
                            lstConnectionString.Add(strConfigFile.Substring(strConfigFile.IndexOf("<add"), strConfigFile.IndexOf("/>") - strConfigFile.IndexOf("<add") + 4));
                            strConfigFile = strConfigFile.Substring(strConfigFile.IndexOf("/>") + 2);
                        }
                        int x = 1;
                        foreach (var connectionString in lstConnectionString)
                        {
                            ProgressInformation("Adding connectionstrings.");
                            ProgressBarValue(30, pbrTableProgressBar);

                            RadioButton radioButton = new RadioButton();
                            radioButton.Text = connectionString;
                            radioButton.Name = "rbnConnectionString_" + x;
                            radioButton.Location = new Point(5, 30*x);
                            radioButton.Width = 750;
                            grpConnectionString.Controls.Add(radioButton);
                            x++;
                        }

                        tabContainer.SelectedTab = tabConnectionString;
                    }
                    else
                    {
                        ProgressInformation("The selected file doesn't have a connectionstring");
                        ProgressBarValue(0, pbrTableProgressBar);
                    }

                }
                catch (Exception ex)
                {
                    ProgressInformation("Error occured: " + ex.Message);
                    ProgressBarValue(0, pbrTableProgressBar);
                }
            }
        }

        #endregion

        #region ProgressInformation

        private void ProgressBarValue(int value, ProgressBar pbrProgressBar)
        {
            if (value <= pbrProgressBar.Maximum)
                pbrProgressBar.Value = value;
           System.Threading.Thread.Sleep(20); // Needed for the gui to update and render all controls
           Application.DoEvents();
        }

        private void ProgressInformation(string text)
        {
            toolStripStatusLabel.Text = text;
        }

        #endregion

        #region ConnectionString

        private void btnConnectionString_OK_Click(object sender, EventArgs e)
        {
            string strConnectionString = string.Empty;

            foreach (RadioButton radioButton in grpConnectionString.Controls)
            {
                if (radioButton.Checked)
                    strConnectionString = radioButton.Text;
            }

            ProgressInformation("Reading selected connectionstring.");
            ProgressBarValue(35, pbrTableProgressBar);

            lblTableSelection_Connectionstring.Text = strConnectionString;

            ProgressInformation("Extracting the connectionstring.");
            ProgressBarValue(45, pbrTableProgressBar);

            strConnectionString = strConnectionString.Substring(strConnectionString.IndexOf("connectionString=\"") + 18);
            strConnectionString = strConnectionString.Substring(0, strConnectionString.IndexOf("\""));

            tabContainer.SelectedTab = tabTableSelection;

            GetTablesFromConnectionstring(strConnectionString);
        }

        private void GetTablesFromConnectionstring(string strConnectionString)
        {
            pnlTables.Enabled = false;
            chkboxSelectAll.Enabled = false;
            ProgressInformation("Preparing to retrive tables.");
            ProgressBarValue(50, pbrTableProgressBar);

            Application.DoEvents();

            GeneratorFeedback generatorFeedback = new GeneratorFeedback();

            _connectionStringDry = strConnectionString;
            try
            {
                Dry.Dry.ConnectionString = strConnectionString;
                var dbTables = DbTable.GetAllDbTables(_tablePrefix);

                pnlTables.Controls.Clear();
                pnlDetails.Controls.Clear();
                pnlErrors.Controls.Clear();

                int x = 1;
                // Create a checkbox for each table
                foreach (var table in dbTables)
                {
                    CheckBox chkBox = new CheckBox();
                    chkBox.Text = table.TableName;
                    chkBox.Name = "chkBoxTable_" + x;
                    chkBox.Location = new Point(5, (20 * x) - 20);
                    chkBox.Width = 390;
                    chkBox.Enabled = false;
                    chkBox.CheckedChanged += chkBoxTable_CheckedChanged;
                    pnlTables.Controls.Add(chkBox);
                    x++;

                    ProgressInformation("Retrieving tabel " + table.TableName + ".");
                    ProgressBarValue(50 + (x * (950 / dbTables.Count)), pbrTableProgressBar);
                    ProgressBarValue(0 + (x * (500 / dbTables.Count)), pbrGenerationProgressBar);
                }

                Label lblInfo = new Label();
                lblInfo.Text = dbTables.Count + " tables retrieved from database.";
                lblInfo.Width = 350;
                lblInfo.Name = "lblInfoTabelRetrieved";
                pnlDetails.Controls.Add(lblInfo);

                lblTableCount.Text = dbTables.Count + " tables";
                ProgressInformation("Tables retrieved from database.");
                ProgressBarValue(1000, pbrTableProgressBar);
                ProgressBarValue(500, pbrGenerationProgressBar);
                pnlTables.Enabled = true;
                btnGenerateBackend.Enabled = true;
                btnGenerateDLL.Enabled = true;
                pnlTables.Focus();
            }
            catch (Exception exception)
            {
                generatorFeedback.Exception = exception;
                ProgressInformation("Error while generating backend.");
                tabControlProgress.SelectTab(tabErrors);
                ShowError(generatorFeedback, "");
            }

            foreach (CheckBox checkBox in pnlTables.Controls)
                checkBox.Enabled = true;

            chkboxSelectAll.Enabled = true;
        }

        private void chkboxSelectAll_CheckedChanged(object sender, EventArgs e)
        {
            foreach (CheckBox checkBox in pnlTables.Controls)
            {
                checkBox.Checked = chkboxSelectAll.Checked;
            }

            CountSelectedTables();
        }

        private void chkBoxTable_CheckedChanged(object sender, EventArgs e)
        {
            CountSelectedTables();
        }

        private void CountSelectedTables()
        {
            int i = 0;
            foreach (CheckBox checkBox in pnlTables.Controls)
                if (checkBox.Checked)
                    i++;

            TimeSpan calcuatedTimeToGenerate = TimeSpan.FromMilliseconds(i * 660);
            string strTimeElapsed = (calcuatedTimeToGenerate.Hours > 0 ? calcuatedTimeToGenerate.Hours + " h " : "") + (calcuatedTimeToGenerate.Minutes > 0 ? calcuatedTimeToGenerate.Minutes + " m " : "") + calcuatedTimeToGenerate.Seconds + " s " + calcuatedTimeToGenerate.Milliseconds + " ms";
            strTimeElapsed = strTimeElapsed.Trim();

            ProgressInformation(i + " tables selected, estimated the to complete " + strTimeElapsed + ".");
        }

        private void btnGenerateBackend_Click(object sender, EventArgs e)
        {
            GenerateBackend();
        }

        private void GenerateBackend()
        {
            DateTime generationStart = DateTime.Now;

            foreach (CheckBox checkBox in pnlTables.Controls)
                checkBox.Enabled = false;

            chkboxSelectAll.Enabled = false;
            pnlTables.Enabled = false;
            btnGenerateBackend.Enabled = false;
            btnGenerateDLL.Enabled = false;

            Application.DoEvents();

            ProgressBarValue(500, pbrGenerationProgressBar);
            ProgressBarValue(0, pbrTableProgressBar);
            ProgressInformation("Creating folders.");

            if (!Directory.Exists(_outputDestination + "\\BO"))
                Directory.CreateDirectory(_outputDestination + "\\BO");

            if (!Directory.Exists(_outputDestination + "\\BO\\AutoGenerated"))
                Directory.CreateDirectory(_outputDestination + "\\BO\\AutoGenerated");

            if (!Directory.Exists(_outputDestination + "\\BLL"))
                Directory.CreateDirectory(_outputDestination + "\\BLL");

            if (!Directory.Exists(_outputDestination + "\\BLL\\AutoGenerated"))
                Directory.CreateDirectory(_outputDestination + "\\BLL\\AutoGenerated");

            if (!Directory.Exists(_outputDestination + "\\IP"))
                Directory.CreateDirectory(_outputDestination + "\\IP");

            if (!Directory.Exists(_outputDestination + "\\IP\\AutoGenerated"))
                Directory.CreateDirectory(_outputDestination + "\\IP\\AutoGenerated");

            if (!Directory.Exists(_outputDestination + "\\DAL"))
                Directory.CreateDirectory(_outputDestination + "\\DAL");

            if (!Directory.Exists(_outputDestination + "\\DAL\\AutoGenerated"))
                Directory.CreateDirectory(_outputDestination + "\\DAL\\AutoGenerated");

            if (!Directory.Exists(_outputDestination + "\\Enums"))
                Directory.CreateDirectory(_outputDestination + "\\Enums");

            if (!Directory.Exists(_outputDestination + "\\Enums\\AutoGenerated"))
                Directory.CreateDirectory(_outputDestination + "\\Enums\\AutoGenerated");

            Dry.Dry.ProjectName = _projectName;
            Dry.Dry.ProjectPath = _outputDestination;
            Dry.Dry.ConnectionString = _connectionStringDry;

            GeneratorFeedback generatorFeedback  = new GeneratorFeedback();

            // Validate the database
            int controlsToGenerate = 0;
            bool isValid = true;
            foreach (CheckBox checkBox in pnlTables.Controls)
            {
                // Only validate tables we have selected
                if (checkBox.Checked)
                {
                    generatorFeedback = Dry.Dry.ValidateTableForBackend(checkBox.Text, _tablePrefix);

                    isValid = !generatorFeedback.HasError;
                    controlsToGenerate++;

                    if (!isValid)
                        break;
                }
            }

            // Generate the backend
            int i = 1;
            int j = 1;
            int lines = 0;

            if (isValid)
            {
                foreach (CheckBox checkBox in pnlTables.Controls)
                {
                    i++;
                    if (checkBox.Checked)
                    {
                        j++;

                        ProgressInformation("Generating backend for table " + checkBox.Text + ".");
                        ProgressBarValue(500 + (i * (500 / controlsToGenerate)), pbrGenerationProgressBar);
                        ProgressBarValue((i * (1000 / controlsToGenerate)), pbrTableProgressBar);

                        // DAL
                        generatorFeedback = Dry.Generators.DALGenerator.CreateFile(checkBox.Text, _mspractices5 ? "5" : "4", _generateDryLog, _tablePrefix, _generateInnerJoinCode);
                        ShowError(generatorFeedback, checkBox.Text);
                        lines += generatorFeedback.Lines;
                        Dry.Generators.DALGenerator.CreateBaseDAL();

                        // BO
                        generatorFeedback = Dry.Generators.BOGenerator.CreateFile(checkBox.Text, _generateLocalization, _tablePrefix);
                        ShowError(generatorFeedback, checkBox.Text);
                        lines += generatorFeedback.Lines;
                        Dry.Generators.BOGenerator.CreateBaseBO();

                        // IP
                        generatorFeedback = Dry.Generators.IPGenerator.CreateFile(checkBox.Text, _tablePrefix);
                        ShowError(generatorFeedback, checkBox.Text);
                        lines += generatorFeedback.Lines;
                        Dry.Generators.IPGenerator.CreateBaseIP();

                        // BLL
                        generatorFeedback = Dry.Generators.BLLGenerator.CreateFile(checkBox.Text, _generateDryLog, _tablePrefix, _generateInnerJoinCode);
                        ShowError(generatorFeedback, checkBox.Text);
                        lines += generatorFeedback.Lines;
                        Dry.Generators.BLLGenerator.CreateBaseBLL();

                        if (checkBox.Text.EndsWith("Enum"))
                        {
                            generatorFeedback = Dry.Generators.EnumGenerator.CreateFile(checkBox.Text);
                            ShowError(generatorFeedback, checkBox.Text);
                            lines += generatorFeedback.Lines;
                        }

                        if (generatorFeedback.HasError)
                            break;

                        Label lblInfo = new Label();
                        lblInfo.Text = "Backend generated for table " + checkBox.Text + ".";
                        lblInfo.Width = 350;
                        lblInfo.Name = "lblGenerate" + checkBox.Text;
                        lblInfo.Location = new Point(0, (20 * j) - 20);
                        pnlDetails.Controls.Add(lblInfo);
                    }
                }

                Dry.Generators.EnumGenerator.CreateTableColumnFile();
            }
            else
                ShowError(generatorFeedback, "");

            ProgressBarValue(1000, pbrGenerationProgressBar);
            ProgressBarValue(1000, pbrTableProgressBar);

            // Show information about how long the generation process took
            DateTime generationEnd = DateTime.Now;
            TimeSpan timeElapsed = generationEnd.Subtract(generationStart);
            string strTimeElapsed = (timeElapsed.Hours > 0 ? timeElapsed.Hours + " h " : "") + (timeElapsed.Minutes > 0 ? timeElapsed.Minutes + " m " : "") + timeElapsed.Seconds + " s " + timeElapsed.Milliseconds + " ms";
            strTimeElapsed = strTimeElapsed.Trim();

            if (generatorFeedback.HasError)
            {
                ProgressInformation("Error while generating backend.");
                tabControlProgress.SelectTab(tabErrors);
            }
            else
                ProgressInformation("Backend successfully generated in " + strTimeElapsed + " (" + lines + " lines written).");

            foreach (CheckBox checkBox in pnlTables.Controls)
                checkBox.Enabled = true;

            chkboxSelectAll.Enabled = true;
            pnlTables.Enabled = true;
            btnGenerateBackend.Enabled = true;
            btnGenerateDLL.Enabled = true;
        }

        public static IEnumerable<FileInfo> GetFilesRecursive(DirectoryInfo dirInfo)
        {
            return GetFilesRecursive(dirInfo, "*.*");
        }
        public static IEnumerable<FileInfo> GetFilesRecursive(DirectoryInfo dirInfo, string searchPattern)
        {
            foreach (DirectoryInfo di in dirInfo.GetDirectories())
                foreach (FileInfo fi in GetFilesRecursive(di, searchPattern))
                    yield return fi;

            foreach (FileInfo fi in dirInfo.GetFiles(searchPattern))
                yield return fi;
        }

        private void btnGenerateDLL_Click(object sender, EventArgs e)
        {
            //Always generate all tables when creating dll
            foreach (CheckBox checkBox in pnlTables.Controls)
            {
                checkBox.Checked = true;
            }

            GenerateBackend();

            if (!Directory.Exists(_outputDestination + "\\DLL"))
                Directory.CreateDirectory(_outputDestination + "\\DLL");

            CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");

            string Output = _outputDestination + "\\DLL\\" + _projectName + ".dll";
            
            DirectoryInfo directoryInfo = new DirectoryInfo(_outputDestination);

            IEnumerable<FileInfo> fileInfos = GetFilesRecursive(directoryInfo);

            List<string> files = new List<string>();
            foreach (FileInfo fileInfo in fileInfos)
            {
                files.Add(fileInfo.FullName);
            }

            CompilerParameters parameters = new CompilerParameters();
            //Make sure we generate an DLL, not an EXE
            parameters.GenerateExecutable = false;
            parameters.OutputAssembly = Output;

            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.ReferencedAssemblies.Add("System.Data.dll");
            parameters.ReferencedAssemblies.Add("System.Data.Linq.dll");
            parameters.ReferencedAssemblies.Add("System.Core.dll");
            parameters.ReferencedAssemblies.Add("System.Xml.dll");
            parameters.ReferencedAssemblies.Add("System.Xml.Linq.dll");
            parameters.ReferencedAssemblies.Add("System.Deployment.dll");
            parameters.ReferencedAssemblies.Add("System.Configuration.dll");
            parameters.ReferencedAssemblies.Add("Microsoft.Practices.EnterpriseLibrary.Data.dll");
            parameters.ReferencedAssemblies.Add("Microsoft.Practices.EnterpriseLibrary.Common.dll");
            if(_mspractices5)
            {
                parameters.ReferencedAssemblies.Add("Microsoft.Practices.EnterpriseLibrary.Common.dll");
            }

            CompilerResults results = codeProvider.CompileAssemblyFromFile(parameters, files.ToArray());

            if (results.Errors.Count > 0)
            {
                ProgressInformation("Error occured when generating dll.");
                foreach (CompilerError CompErr in results.Errors)
                {
                    ShowError(new GeneratorFeedback()
                    {
                        Exception = new Exception("Line number " + CompErr.Line + ", Error Number: " + CompErr.ErrorNumber + ", '" + CompErr.ErrorText)
                        ,HasError = true
                    }, "");
                }
            }
            else
            {
                ProgressInformation("DLL successfully generated.");
            }
        }

        protected void ShowError(GeneratorFeedback generatorFeedback, string extra)
        {
            if(generatorFeedback.Exception != null)
            {
                Label lblInfo = new Label();
                if (generatorFeedback.Exception.InnerException != null)
                    lblInfo.Text = (extra != "" ? extra + ": " : "") + "Exception " + generatorFeedback.Exception.Message + " " + generatorFeedback.Exception.InnerException.Message;
                else
                    lblInfo.Text = (extra != "" ? extra + ": " : "") + "Exception " + generatorFeedback.Exception.Message;
                lblInfo.Width = 5000;
                lblInfo.Name = "lblIGeneratorError";
                pnlErrors.Controls.Add(lblInfo);
            }
        }

        #endregion

        #region Favorites

        private void btnCreateFavorite_Click(object sender, EventArgs e)
        {
            if (txtCreateFavorite_FavoriteName.Text != "")
            {
                var xmlDocument = new XmlDocument();
                xmlDocument.Load(XmlFavorites);

                XmlElement xmlElement = xmlDocument.CreateElement("favorite");

                // 1. Create the child nodes.
                xmlElement.InnerXml = "<name></name><connectionstring></connectionstring>";

                xmlElement["name"].InnerText                = txtCreateFavorite_FavoriteName.Text;
                xmlElement["namespace"].InnerText           = txtNamespace.Text;
                xmlElement["connectionstring"].InnerText    = txtCreateFavorite_ConnectionString.Text;
                xmlElement["outputDestination"].InnerText   = txtCreateFavorite_OutputDestination.Text;
                xmlElement["mspractices5"].InnerText        = chkMSPractices5.Checked.ToString();
                xmlElement["generatedrylog"].InnerText      = cbxGenerateDryLog.Checked.ToString();
                xmlElement["localization"].InnerText        = cbxGenerateLocalization.Checked.ToString();
                xmlElement["tableprefix"].InnerText         = txtTablePrefix.Text;

                // 2. Add the new element to the end of the item list.
                xmlDocument.DocumentElement.SelectNodes("/favorites")[0].AppendChild(xmlElement);

                // 3. Save the modified XML to a file in Unicode format.
                xmlDocument.PreserveWhitespace = true;
                var xmlTextWriter = new XmlTextWriter(XmlFavorites, System.Text.Encoding.Unicode);
                xmlDocument.WriteTo(xmlTextWriter);
                xmlTextWriter.Close();

                ProgressBarValue(100, pbrTableProgressBar);
                ProgressInformation("Favorit sparad");

                ProcessXml(XmlFavorites);
            }
        }

        public void DisplayFavorite(string xml, string name)
        {
            // Store the favorite xml in the list item value so that all of its properites can be get when selected
            var li = new ListItem { Value = xml, Text = name };
            lstBoxFavorites.Items.Add(li);            
        }

        private XmlTextReader LoadXmlFromFile(string fileName)
        {
            // Read the xml from a file
            XmlTextReader reader = new XmlTextReader(fileName);
            reader.Read();

            return reader;
        }

        public void ProcessXml(String xmlFile)
        {
            lstBoxFavorites.Items.Clear();
            try
            {
                // Get all favorites from the xml file
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(LoadXmlFromFile(xmlFile));

                XmlNodeList xmlNodeList = xmlDocument.SelectNodes("//favorites/favorite");

                List<FavoriteProjects> lstFavoritProjects = new List<FavoriteProjects>();

                for (int i = 0; i < xmlNodeList.Count; i++)
                {
                    FavoriteProjects favoriteProject = new FavoriteProjects();

                    favoriteProject.Name = xmlNodeList.Item(i).SelectSingleNode("name").InnerText;
                    favoriteProject.ConnectionString = xmlNodeList.Item(i).SelectSingleNode("connectionstring").InnerText;
                    favoriteProject.OutputDestination = xmlNodeList.Item(i).SelectSingleNode("outputDestination").InnerText;
                    favoriteProject.Xml = xmlNodeList.Item(i).InnerXml;

                    // Add the favorite to the list
                    if (favoriteProject.IsValid())
                        lstFavoritProjects.Add(favoriteProject);                        
                }

                lstFavoritProjects = lstFavoritProjects.OrderBy(fp => fp.Name).ToList();

                foreach (FavoriteProjects fp in lstFavoritProjects)
                {
                    DisplayFavorite("<favorite>" + fp.Xml + "</favorite>", fp.Name);
                }

                    

            }
            catch (Exception ex)
            {
                toolStripStatusLabel.Text = "Problem uppstod vid laddande av favoriter: " + ex.Message;
            }
        }

        public class FavoriteProjects
        {
            public string Name { get; set; }
            public string ConnectionString { get; set; }
            public string OutputDestination { get; set; }
            public string Xml { get; set; }

            public bool IsValid()
            {
                return Name != "" && ConnectionString != "" && OutputDestination != "";
            }
        }

        private void lstBoxFavorites_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstBoxFavorites.SelectedItem != null)
            {
                XmlDocument xmlDocument = new XmlDocument();

                // Get the xml from the selected list item
                xmlDocument.LoadXml(((ListItem) lstBoxFavorites.SelectedItem).Value);

                // Get the propteries of the favorite
                string connectionstring     = xmlDocument.SelectSingleNode("//favorite/connectionstring").InnerText;

                _outputDestination          = xmlDocument.SelectSingleNode("//favorite/outputDestination").InnerText;
                _projectName                = xmlDocument.SelectSingleNode("//favorite/namespace") != null ? xmlDocument.SelectSingleNode("//favorite/namespace").InnerText : xmlDocument.SelectSingleNode("//favorite/name").InnerText;
                _mspractices5               = xmlDocument.SelectSingleNode("//favorite/mspractices5") != null ? bool.Parse(xmlDocument.SelectSingleNode("//favorite/mspractices5").InnerText) : false;
                _tablePrefix                = xmlDocument.SelectSingleNode("//favorite/tableprefix") != null ? xmlDocument.SelectSingleNode("//favorite/tableprefix").InnerText : "tbl";
                _generateDryLog             = xmlDocument.SelectSingleNode("//favorite/generatedrylog") != null ? bool.Parse(xmlDocument.SelectSingleNode("//favorite/generatedrylog").InnerText) : false;
                _generateLocalization       = xmlDocument.SelectSingleNode("//favorite/localization") != null ? bool.Parse(xmlDocument.SelectSingleNode("//favorite/localization").InnerText) : false;
                _generateInnerJoinCode      = xmlDocument.SelectSingleNode("//favorite/generateInnerJoinCode") != null ? bool.Parse(xmlDocument.SelectSingleNode("//favorite/generateInnerJoinCode").InnerText) : false;

                Text = "Dry Code Generator - " + ((ListItem)lstBoxFavorites.SelectedItem).Text;

                // Change tab in hte GUI
                tabContainer.SelectedTab = tabTableSelection;

                // Use the connection string property to get all the tables in the database
                GetTablesFromConnectionstring(connectionstring);
            }
        }

        #endregion

        /// <summary>
        /// The user is resizing dry
        /// </summary>
        private void DRY_Resize(object sender, EventArgs e)
        {
            ResizeControls();
        }
        
        /// <summary>
        /// Resize the entire controls and change apperance after the new window size
        /// </summary>
        private void ResizeControls()
        {

            tabContainer.Width = this.Size.Width - 40;
            tabContainer.Height = this.Size.Height - tabContainer.Top - statusStrip.Height - menuStrip.Height - 20;

            // Favorites
            grpCreateFavorite.Left = tabContainer.Width - grpCreateFavorite.Width - 15;
            grpCreateFavorite.Height = tabContainer.Height - grpCreateFavorite.Top - 35;

            grpFavorites.Width = tabContainer.Width - grpCreateFavorite.Width - 30;
            grpFavorites.Height = tabContainer.Height - grpFavorites.Top - 35;

            pnlFavorites.Width = grpFavorites.Width - 10;
            pnlFavorites.Height = grpFavorites.Height - 10;

            lstBoxFavorites.Width = pnlFavorites.Width - 10;
            lstBoxFavorites.Height = pnlFavorites.Height - lstBoxFavorites.Top - 10;

            txtFile.Width = tabContainer.Width - btnFileOk.Width - 25;
            btnFileOk.Left = txtFile.Width + 10;

            // Connection strings
            grpConnectionString.Width = tabContainer.Width - 15;
            grpConnectionString.Height = tabContainer.Height - grpTables.Top - 60;

            btnConnectionString_OK.Top = tabContainer.Height - pbrTableProgressBar.Height - 30;

            // Tables
            grpTables.Width = tabContainer.Width - 15;
            grpTables.Height = tabContainer.Height - grpTables.Top - 35;

            lblTableCount.Left = grpTables.Width - lblTableCount.Width - 5;

            pnlTables.Width = grpTables.Width - 15;
            pnlTables.Height = grpTables.Height - pnlTables.Top - 150;

            btnGenerateBackend.Top = pnlTables.Height + 45;
            btnGenerateBackend.Left = grpTables.Width - btnGenerateBackend.Width - 7;

            btnGenerateDLL.Top = btnGenerateBackend.Top + 23;
            btnGenerateDLL.Left = btnGenerateBackend.Left;

            pbrTableProgressBar.Top = pnlTables.Height + 45;
            pbrTableProgressBar.Width = grpTables.Width - btnGenerateBackend.Width - 25;

            pbrGenerationProgressBar.Top = pnlTables.Height + 60;
            pbrGenerationProgressBar.Width = grpTables.Width - btnGenerateBackend.Width - 25;

            tabControlProgress.Top = pnlTables.Height + 72;
            tabControlProgress.Width = grpTables.Width - 15;
            tabControlProgress.Height = 115;

            pnlDetails.Width = tabControlProgress.Width - 20;
            pnlDetails.Height = tabControlProgress.Height - 35;

            pnlErrors.Width = tabControlProgress.Width - 20;
            pnlErrors.Height = tabControlProgress.Height - 35;
            
        }

        /// <summary>
        /// Exit button in the menu is pressed
        /// </summary>
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        /// <summary>
        /// About button in the menu is pressed
        /// </summary>
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox aboutBox = new AboutBox();
            aboutBox.Show();
        }

        private void howDoIToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormHowTo howTo = new FormHowTo();
            howTo.Icon = this.Icon;
            howTo.Show();
        }
    }
}
